import { Injectable } from '@nestjs/common';
import * as Sequelize from 'sequelize';
import sequelize  from 'src/database/sequelize';
import { makeSalt,encryptPassword } from '../../utils/cryptogram'; //引入加密函数
import { log } from 'console';

@Injectable()
export class UserService {
async findOne(username: string): Promise<any | undefined> {   
  const sql=`select user_id id,real_name realName,role,passwd password,account_name username,passwd_salt salt,mobile  from admin_user where account_name='${username}'`
     try{
      const res=  await sequelize.query(sql,{
            type:Sequelize.QueryTypes.SELECT,
            raw:true,//是否使用数组方式展示结果
            logging:true,//是否打印日志
        });
        if(res.length>0){
            const user=res[0]
            if(user){
                return user
            }else{
                return  {
                    code :500,
                    msg:'该用户不存在'
                }
            }
        }else{
            return  {
                code :500,
                msg:'该用户不存在',
                data:null,
            }
        }
    
     }catch(error){
        return {
            code:503,
            msg:`Service error :${error}`
        }
     }
}
async register(requestBody:any) :Promise<any>{
const {accountName,realName,password,repassword,mobile} =requestBody;
  if(password!== repassword){
      return {
          code:400,
          msg:'两次密码不一致'
      }
  }
const user =await this.findOne(accountName);
if( user.code !== 500 ){
    return {
        code:400,
        msg:'该账号已存在'
    }
}
const salt  = makeSalt(); //制作密码
const hashPwd = encryptPassword(password,salt); //加密密码
const registerSQL=`insert into admin_user (account_name,real_name,passwd,passwd_salt,mobile,user_status,role,create_by) values ('${accountName}','${realName}','${hashPwd}','${salt}','${mobile}',1,3,0)`
try{
   await sequelize.query(registerSQL,{logging:false});
   return {
    code:200,
    msg:'success'
}
}catch(error){
    return {
        code :503,
        msg:"Service error :${error}"
    };
}
}
}